package shop.up.product.service.impl;

import com.alibaba.nacos.client.utils.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import shop.up.product.service.TestService;

import javax.annotation.Resource;

/**
 * @author zzc
 * @date 2023/4/4 15:33
 */
@Service
public class TestServiceImpl implements TestService {

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    @Override
    public synchronized void testLock() {
        // 创建锁：
        String skuId = "25";
        String locKey = "lock:" + skuId;
        RLock lock = redissonClient.getLock(locKey);
        lock.lock();
        // 业务逻辑代码
        // 获取数据
        String value = redisTemplate.opsForValue().get("num");
        if (StringUtils.isBlank(value)) {
            return;
        }
        // 将value 变为int
        int num = Integer.parseInt(value);
        // 将num +1 放入缓存
        redisTemplate.opsForValue().set("num", String.valueOf(++num));
        lock.unlock();
    }
}
